package www.openteam.com.adapter.policy;

import android.content.Context;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.util.SortedList;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.bean.OrderApprovalitem;
import www.openteam.com.bean.ProOrder;

/**
 * Created by kylin on 2016/9/26.
 */

public class PrOrderAdapter extends RecyclerView.Adapter {


    private static final String TAG = "PrOrderAdapter";

    private LayoutInflater mLayoutInflater;
    private SortedList<ProOrder.DataEntity> mSortedList;
    private ArrayList<OrderApprovalitem> orderApprovalitems = new ArrayList<OrderApprovalitem>();
    OrderApprovalitem orderApprovalitem = null;
    StringBuilder sb = new StringBuilder();
    private ButtonInterfacet buttonInterfacet;
    private Context context;
    private VHInterface vHInterface;
    List<Boolean> isflag = new ArrayList<>();
    public OnLineClickListener onLineClickListener;


    public interface OnLineClickListener{
        void onClick(ProOrder.DataEntity item);
    }

    public void setOnLineClickListener(OnLineClickListener onLineClickListener) {
        this.onLineClickListener = onLineClickListener;
    }

    public PrOrderAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
//        Log.d(TAG, "DataAdapter: 1");
        mSortedList = new SortedList<>(ProOrder.DataEntity.class, new SortedList.Callback<ProOrder.DataEntity>() {

            /**
             * 返回一个负整数（第一个参数小于第二个）、零（相等）或正整数（第一个参数大于第二个）
             */
            @Override
            public int compare(ProOrder.DataEntity o1, ProOrder.DataEntity o2) {

                if (Integer.parseInt(o1.getRownumber()) < Integer.parseInt(o2.getRownumber())) {
                    return -1;
                } else if (Integer.parseInt(o1.getRownumber()) > Integer.parseInt(o2.getRownumber())) {
                    return 1;
                }

                return 0;
            }

            @Override
            public boolean areContentsTheSame(ProOrder.DataEntity oldItem, ProOrder.DataEntity newItem) {
                Log.d(TAG, "areContentsTheSame: " + 1);
                return oldItem.getRownumber().equals(newItem.getRownumber());
            }

            @Override
            public boolean areItemsTheSame(ProOrder.DataEntity item1, ProOrder.DataEntity item2) {

                return item1.getRdsno().equals(item2.getRdsno());
            }

            @Override
            public void onInserted(int position, int count) {
                notifyItemRangeInserted(position, count);
            }

            @Override
            public void onRemoved(int position, int count) {
                notifyItemRangeRemoved(position, count);
            }

            @Override
            public void onMoved(int fromPosition, int toPosition) {
                notifyItemMoved(fromPosition, toPosition);
            }

            @Override
            public void onChanged(int position, int count) {
                notifyItemRangeChanged(position, count);
            }
        });
    }

    public void changeData(int change, String statue) {
        mSortedList.get(change).setStatusn(statue);
    }

    public void addItems(ArrayList<ProOrder.DataEntity> list) {
        mSortedList.beginBatchedUpdates();
        for (ProOrder.DataEntity itemModel : list) {
            mSortedList.add(itemModel);
            isflag.add(false);
        }
        mSortedList.endBatchedUpdates();
    }

    public void addContext(Context context) {
        this.context = context;
    }

    public void deleteItems(ArrayList<ProOrder.DataEntity> items) {
        mSortedList.beginBatchedUpdates();
        for (ProOrder.DataEntity item : items) {
            mSortedList.remove(item);
        }
        mSortedList.endBatchedUpdates();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//        Log.d(TAG, "DataAdapter: 3");
        return new mViewHolder(mLayoutInflater.inflate(R.layout.item_auditing, parent, false), context);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
//        Log.d(TAG, "DataAdapter:4");
        mViewHolder viewHolder = (mViewHolder) holder;
        final ProOrder.DataEntity item = mSortedList.get(position);
//        String[] prodname = item.getProdname().split(";");
//        String[] prodno = item.getProdno().split(",");
////
//        Float[] price = splitStringFloat(item.getPrice(), "price");
//        Float[] paynumb =splitStringFloat(item.getPaynumb(),"numb");


//        for (int i = 0; i < prodno.length; i++) {
//            orderApprovalitem= new OrderApprovalitem();
//            orderApprovalitem.setProdno(prodno[i]);
//            orderApprovalitem.setProdname(prodname[i]);
//            orderApprovalitem.setNumb(paynumb[i]);
//            orderApprovalitem.setPrice(price[i]);
//            orderApprovalitems.add(orderApprovalitem);
//        }

//        for (OrderApprovalitem oa:orderApprovalitems) {
//            sb.append("产品编号:"+oa.getProdno()).append("\n").append("产品名称:"+oa.getProdname()).append("\n")
//                    .append("价格:"+oa.getNumb()+" * "+oa.getPrice()+" = ").append(oa.getPaynumb()*oa.getPrice()).append("\n");
//        }
        viewHolder.doubleOnclick(new mViewHolder.DoubleInterfacet() {
            @Override
            public void doubleClickSelect() {
                vHInterface.onclick(position);
            }
        });
        String CustName = "";
        if (!item.getCustSName().equals(null)) {
            CustName = item.getCustSName();
        } else {
            CustName = item.getCustname();
        }
        if (item.getStatusn().equals("已审核")) {
            viewHolder.a_card.setCardBackgroundColor(context.getResources().getColor(R.color.red_shallow));
        } else if (item.getStatusn().equals("未审核")) {
            viewHolder.a_card.setCardBackgroundColor(context.getResources().getColor(R.color.green));
        } else {
            viewHolder.a_card.setCardBackgroundColor(context.getResources().getColor(R.color.gray));
        }
        if (isflag.get(position)){
            viewHolder.a_card.setCardBackgroundColor(context.getResources().getColor(R.color.actionbar_background));
        }
        viewHolder.rela.setVisibility(View.GONE);
//        viewHolder.textView.setText(item.getRownumber() + "");
        viewHolder.NRdson.setText("采购单号:");
        viewHolder.NCustorderid.setText("采购商名称:");
//        viewHolder.NBusinessno.setText("订购时间:");
        viewHolder.NMoney.setText("合计:");
        viewHolder.Rdson.setText(item.getRdsno());
        viewHolder.Custorderid.setText(CustName);
        viewHolder.textView.setText(item.getInputdate());
        viewHolder.Money.setText(item.getOrderamount() + "(" + item.getMoneyName() + ")");
        viewHolder.lineitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onLineClickListener!=null){
                    int size = isflag.size();
                    for (int i = 0; i < size; i++) {
                        isflag.set(i, false);
                    }
                    isflag.set(position, true);
                    notifyDataSetChanged();
                    onLineClickListener.onClick(item);
                }
            }
        });

        Log.e(TAG, "onBindViewHolder: position"+position+"--status:"+item.getStatusn() );

//        viewHolder.tv_title.setText(
//                "采购单号:" + item.getRdsno() + "\n"
//                        + "采购商名称:" + CustName
//                        + "\n订购时间" + item.getInputdate() + "\n"
//                        + "合计:" + item.getOrderamount() + "(" + item.getMoneyName() + ")\n" +
//                        "状态:" + item.getStatusn()
//        );
//        orderApprovalitems.clear();
//        sb.setLength(0);
//        sb.delete(0, sb.length());

        viewHolder.btn_autding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//审核

                if (buttonInterfacet != null) {
//                  接口实例化后的而对象，调用重写后的方法
                    buttonInterfacet.onclick(v, position);
                }

            }
        });
    }

    /**
     * 按钮点击事件需要的方法
     */
    public void buttonSetOnclick(ButtonInterfacet buttonInterfacet) {
        this.buttonInterfacet = buttonInterfacet;
    }

    /**
     * 按钮点击事件对应的接口
     */
    public interface ButtonInterfacet {
        public void onclick(View view, int position);
    }


    /**
     * 双击viewHolder需要的方法
     */
    public void vHSetOnclick(VHInterface vHInterface) {
        this.vHInterface = vHInterface;
    }

    /**
     * 按钮点击事件对应的接口
     */
    public interface VHInterface {
        void onclick(int position);
    }

    @Override
    public int getItemCount() {

//        Log.d(TAG, "getItemCount: " +mSortedList.size());
        return mSortedList.size();
    }

    static class mViewHolder extends RecyclerView.ViewHolder {

        private TextView textView;
        private TextView tv_title;
        private Button btn_autding;
        private CardView a_card;
        @Bind(R.id.NRdson)
        TextView NRdson;
        @Bind(R.id.Rdson)
        TextView Rdson;
        @Bind(R.id.NCustorderid)
        TextView NCustorderid;
        @Bind(R.id.Custorderid)
        TextView Custorderid;
//        @Bind(R.id.NBusinessno)
//        TextView NBusinessno;
//        @Bind(R.id.Businessno)
//        TextView Businessno;
        @Bind(R.id.NMoney)
        TextView NMoney;
        @Bind(R.id.Money)
        TextView Money;
        @Bind(R.id.lineitem)
        LinearLayout lineitem;
        @Bind(R.id.rela)
        RelativeLayout rela;
        private MyGestureDetector myGestureDetector;
        private DoubleInterfacet doubleInterfacet;
        public GestureDetectorCompat gestureDetectorCompat;

        public mViewHolder(View itemView, Context context) {
            super(itemView);
//            Log.d(TAG, "DataAdapter: 5");
            textView = (TextView) itemView.findViewById(R.id.tv_id);
//            tv_title = (TextView) itemView.findViewById(R.id.tv_title);
            btn_autding = (Button) itemView.findViewById(R.id.btn_auditing);
            a_card = (CardView) itemView.findViewById(R.id.a_card);
            ButterKnife.bind(this,itemView);
            if (myGestureDetector == null) {
                myGestureDetector = new MyGestureDetector();
            }


            gestureDetectorCompat = new GestureDetectorCompat(context, new MyGestureDetector());
            a_card.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    gestureDetectorCompat.onTouchEvent(event);
                    return true;
                }
            });
        }

        public class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
            private String TAG = OrderAdapter.mViewHolder.MyGestureDetector.class.getSimpleName();

            @Override
            public boolean onDoubleTap(MotionEvent e) {

//                if (buttonTouchEvent != null){
                doubleInterfacet.doubleClickSelect();
                Log.d(TAG, "onDoubleTapEvent: ");
//                }
                return false;
            }


        }


        public void doubleOnclick(DoubleInterfacet doubleInterfacet) {
            this.doubleInterfacet = doubleInterfacet;
        }

        /**
         * 按钮点击事件需要的方法
         */
        public interface DoubleInterfacet {
            void doubleClickSelect();
        }
    }
}